//
//  CartView.swift
//  CMB250716
//
//  Created by Andy Lau on 16/7/25.
//

import SwiftUI

struct CartView: View {
    @EnvironmentObject var dataManager: DataManager
    @State private var showingPayment = false
    @State private var appliedCoupon: Coupon?
    @State private var showingCouponSelection = false
    @State private var pointsToUse = 0
    @State private var showingPointsInput = false
    @State private var showingOrderTypeSelection = false
    @State private var showingQRScanner = false
    @State private var scannedCode: String? = nil
    // 移除优惠券错误提示相关状态变量
    @State private var reservationTime: Date? = nil // 预订时间
    @State private var showingReservationFlow = false
    @State private var reservationInfo: ReservationConfig.ReservationInfo? = nil
    
    // 检查购物车中是否有Cash Voucher
    var hasCashVoucher: Bool {
        dataManager.cartItems.contains { $0.menuItem.name == AppConfig.Cart.voucherPackageName }
    }
    
    // 检查购物车是否只有Cash Voucher
    var hasOnlyCashVoucher: Bool {
        let cashVoucherItems = dataManager.cartItems.filter { $0.menuItem.name == AppConfig.Cart.voucherPackageName }
        return !cashVoucherItems.isEmpty && cashVoucherItems.count == dataManager.cartItems.count
    }
    
    // 获取非Cash Voucher商品的总价
    var nonCashVoucherTotal: Double {
        dataManager.cartItems
            .filter { $0.menuItem.name != AppConfig.Cart.voucherPackageName }
            .reduce(0) { $0 + $1.totalPrice }
    }
    
    // 获取Cash Voucher商品的总价
    var cashVoucherTotal: Double {
        dataManager.cartItems
            .filter { $0.menuItem.name == AppConfig.Cart.voucherPackageName }
            .reduce(0) { $0 + $1.totalPrice }
    }
    
    // 税前小计（从含税价格倒算）
    var subtotalBeforeGST: Double {
        if hasOnlyCashVoucher {
            // 如果只有Cash Voucher，直接返回其价格（无GST）
            return cashVoucherTotal
        } else if hasCashVoucher {
            // 如果有Cash Voucher和其他商品，只对非Cash Voucher商品计算GST
            return (nonCashVoucherTotal / 1.09) + cashVoucherTotal
        } else {
            // 正常情况
            return dataManager.cartTotal / 1.09
        }
    }
    
    // 折扣金额
    var discount: Double {
        // 如果只有Cash Voucher，不应用任何折扣
        if hasOnlyCashVoucher {
            return 0.0
        }
        
        var totalDiscount = 0.0
        
        // 优惠券折扣（基于税前价格计算，只应用于非Cash Voucher商品）
        if let coupon = appliedCoupon {
            totalDiscount += calculateCouponDiscount(coupon: coupon)
        }
        
        // 根据会员级别计算积分抵扣（只应用于非Cash Voucher商品）
        let membershipLevel = dataManager.currentUser?.membershipLevel ?? .lv1
        if pointsToUse >= membershipLevel.minimumPointsForDiscount {
            let discountGroups = pointsToUse / membershipLevel.pointsPerDiscount
            totalDiscount += Double(discountGroups) * 5.0 // 每组抵扣5元
        }
        
        return totalDiscount
    }
    
    // 折扣后的税前小计
    var subtotalAfterDiscount: Double {
        if hasOnlyCashVoucher {
            // 如果只有Cash Voucher，返回其价格（无折扣）
            return cashVoucherTotal
        } else if hasCashVoucher {
            // 如果有Cash Voucher和其他商品，只对非Cash Voucher商品应用折扣
            let nonCashVoucherSubtotal = nonCashVoucherTotal / 1.09
            let discountedNonCashVoucherSubtotal = max(0, nonCashVoucherSubtotal - discount)
            return discountedNonCashVoucherSubtotal + cashVoucherTotal
        } else {
            // 正常情况
            return max(0, subtotalBeforeGST - discount)
        }
    }
    
    // GST税额（基于折扣后的税前价格，Cash Voucher不计入GST）
    var tax: Double {
        if hasOnlyCashVoucher {
            // 如果只有Cash Voucher，无GST
            return 0.0
        } else if hasCashVoucher {
            // 如果有Cash Voucher和其他商品，只对非Cash Voucher商品计算GST
            let nonCashVoucherSubtotal = nonCashVoucherTotal / 1.09
            let discountedNonCashVoucherSubtotal = max(0, nonCashVoucherSubtotal - discount)
            return discountedNonCashVoucherSubtotal * 0.09
        } else {
            // 正常情况
            return subtotalAfterDiscount * 0.09
        }
    }
    
    // 最终总价
    var total: Double {
        subtotalAfterDiscount + tax
    }
    
    // MARK: - 优惠券折扣计算
    private func calculateCouponDiscount(coupon: Coupon) -> Double {
        // 如果只有Cash Voucher，不应用优惠券
        if hasOnlyCashVoucher {
            return 0.0
        }
        
        switch coupon.code {
        case "HIGHBALL":
            // Highball礼券每周每单仅限使用一次，仅可抵扣1杯Highball的价格（S$10）
            let hasHighball = dataManager.cartItems.contains { 
                $0.menuItem.name == "Highball" && $0.menuItem.name != AppConfig.Cart.voucherPackageName
            }
            return hasHighball ? 10.0 : 0.0
            
        case "CALFCOFFEE":
            // Coffee礼券每周每单仅限使用一次，仅可抵扣1杯指定咖啡的S$2额度
            // 仅适用于Americano/Latte/Cappuccino
            let hasEligibleCoffee = dataManager.cartItems.contains { item in
                item.menuItem.name != AppConfig.Cart.voucherPackageName &&
                (item.menuItem.name == "美式咖啡" ||
                 item.menuItem.name == "Americano" ||
                 item.menuItem.name == "拿铁咖啡" ||
                 item.menuItem.name == "Caffe Latte" ||
                 item.menuItem.name == "卡布奇诺" ||
                 item.menuItem.name == "Cappuccino")
            }
            return hasEligibleCoffee ? 2.0 : 0.0
            
        case "MYSTERYGIFT":
            // 神秘礼物本身是免费的，不产生折扣
            return 0.0
            
        default:
            // 其他优惠券使用标准计算方法，但只应用于非Cash Voucher商品
            if hasCashVoucher {
                let nonCashVoucherSubtotal = nonCashVoucherTotal / 1.09
                return coupon.calculateDiscount(for: nonCashVoucherSubtotal)
            } else {
                return coupon.calculateDiscount(for: subtotalBeforeGST)
            }
        }
    }
    
    // 折扣描述文本
    var discountDescription: String {
        var descriptions: [String] = []
        
        // 优惠券折扣描述
        if let coupon = appliedCoupon {
            switch coupon.code {
            case "HIGHBALL":
                let description = dataManager.currentLanguage == "zh" ? "Highball 优惠券" : "Highball Voucher"
                descriptions.append(description)
            case "CALFCOFFEE":
                let description = dataManager.currentLanguage == "zh" ? "免费咖啡优惠券" : "Free Coffee Voucher"
                descriptions.append(description)
            default:
                let couponName = dataManager.currentLanguage == "zh" ? coupon.title : coupon.englishTitle
                let voucherSuffix = dataManager.currentLanguage == "zh" ? "优惠券" : "Voucher"
                descriptions.append("\(couponName) \(voucherSuffix)")
            }
        }
        
        // 积分抵扣描述
        let membershipLevel = dataManager.currentUser?.membershipLevel ?? .lv1
        if pointsToUse >= membershipLevel.minimumPointsForDiscount {
            let pointsDescription = dataManager.currentLanguage == "zh" ? "积分抵扣" : "Points Discount"
            descriptions.append(pointsDescription)
        }
        
        if descriptions.isEmpty {
            return dataManager.currentLanguage == "zh" ? "折扣" : "Discount"
        } else if descriptions.count == 1 {
            return descriptions[0]
        } else {
            let separator = dataManager.currentLanguage == "zh" ? " + " : " + "
            return descriptions.joined(separator: separator)
        }
    }
    
    var body: some View {
        NavigationView {
            VStack(spacing: 0) {
                if dataManager.cartItems.isEmpty {
                    emptyCartView
                } else {
                    ScrollView {
                        VStack(spacing: 0) {
                            // 购物车列表
                            cartItemsList
                            
                            // 优惠券和积分区域
                            discountSection
                            
                            // 价格汇总
                            priceBreakdown
                            
                            // 结算按钮
                            checkoutButton
                        }
                    }
                    .applyScrollIndicatorsIfAvailable()
                }
            }
            .background(
                LinearGradient(
                    colors: [
                        Color(red: 0.0, green: 0.0, blue: 0.0),
                        Color(red: 0.05, green: 0.02, blue: 0.08),
                        Color(red: 0.08, green: 0.04, blue: 0.12),
                        Color(red: 0.12, green: 0.06, blue: 0.15),
                        Color(red: 0.15, green: 0.08, blue: 0.18),
                        Color(red: 0.18, green: 0.10, blue: 0.20),
                        Color(red: 0.20, green: 0.12, blue: 0.22),
                        Color(red: 0.22, green: 0.14, blue: 0.25)
                    ],
                    startPoint: .topLeading,
                    endPoint: .bottomTrailing
                )
                .ignoresSafeArea()
            )
            
            .preferredColorScheme(.dark)
            .navigationBarItems(trailing: 
                !dataManager.cartItems.isEmpty ? 
                Button(action: {
                    dataManager.clearCart()
                }) {
                    Text(dataManager.currentLanguage == "zh" ? AppStrings.CartView.clear : AppStrings.CartView.clearEn)
                        .foregroundColor(.red)
                } : nil
            )
        }
        .sheet(isPresented: $showingPayment) {
            PaymentView(
                subtotal: subtotalBeforeGST,
                tax: tax,
                discount: discount,
                total: total,
                appliedCoupon: appliedCoupon,
                pointsUsed: pointsToUse,
                reservationTime: reservationTime,
                reservationInfo: reservationInfo
            )
            .environmentObject(dataManager)
        }
        .sheet(isPresented: $showingCouponSelection) {
            CouponSelectionView(selectedCoupon: $appliedCoupon)
                .environmentObject(dataManager)
        }
        .sheet(isPresented: $showingOrderTypeSelection) {
            OrderTypeSelectionView(
                onDineIn: {
                    dataManager.selectedDiningType = .dineIn
                    reservationTime = nil
                    reservationInfo = nil
                    showingOrderTypeSelection = false
                    // 确保在主线程上延迟触发QR扫描，避免sheet切换冲突
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                        showingQRScanner = true
                    }
                },
                onTakeAway: {
                    dataManager.selectedDiningType = .takeaway
                    reservationTime = nil
                    reservationInfo = nil
                    showingOrderTypeSelection = false
                    showingPayment = true
                },
                onReservation: {
                    showingOrderTypeSelection = false
                    showingReservationFlow = true
                }
            )
            .environmentObject(dataManager)
        }
        .sheet(isPresented: $showingReservationFlow) {
            ReservationFlowView(
                isPresented: $showingReservationFlow,
                onReservationConfirmed: { info in
                    reservationInfo = info
                    reservationTime = info.reservationTime
                    // 预订总是设置为堂食类型
                    dataManager.selectedDiningType = .dineIn
                    showingPayment = true
                },
                onImmediateDineIn: {
                    showingQRScanner = true
                },
                onImmediateTakeAway: {
                    dataManager.selectedDiningType = .takeaway
                    reservationTime = nil
                    reservationInfo = nil
                    showingPayment = true
                }
            )
            .environmentObject(dataManager)
        }
        .sheet(isPresented: $showingQRScanner) {
            QRCodeScannerView(scannedCode: $scannedCode)
                .onReceive(NotificationCenter.default.publisher(for: .init(QRScannerConfig.Notifications.qrCodeScannedNotification))) { notification in
                if let parsedTableNumber = notification.object as? String {
                    // 直接使用已解析的桌号
                    dataManager.currentTableNumber = parsedTableNumber
                    // 确保在主线程上更新UI状态
                    DispatchQueue.main.async {
                        showingQRScanner = false
                        // 延迟显示支付页面，确保QR扫描器完全关闭
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                            showingPayment = true
                        }
                    }
                }
            }
                .onChange(of: scannedCode) { newValue in
                    if let parsedTableNumber = newValue {
                        // 备用处理逻辑 - 直接使用已解析的桌号
                        dataManager.currentTableNumber = parsedTableNumber
                        DispatchQueue.main.async {
                            showingQRScanner = false
                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                                showingPayment = true
                            }
                        }
                    }
                }
        }
        .alert(dataManager.currentLanguage == "zh" ? AppStrings.CartView.usePoints : AppStrings.CartView.usePointsEn, isPresented: $showingPointsInput) {
            TextField(dataManager.currentLanguage == "zh" ? AppStrings.CartView.pointsQuantity : AppStrings.CartView.pointsQuantityEn, value: $pointsToUse, format: .number)
                .keyboardType(.numberPad)
            
            Button("OK") {
                let maxPoints = dataManager.currentUser?.points ?? 0
                let membershipLevel = dataManager.currentUser?.membershipLevel ?? .lv1
                
                // 如果只有Cash Voucher，不能使用积分
                if hasOnlyCashVoucher {
                    pointsToUse = 0
                    return
                }
                
                // 计算最大可用积分（基于金额限制，只考虑非Cash Voucher商品）
                let baseAmount = hasCashVoucher ? (nonCashVoucherTotal / 1.09) : subtotalBeforeGST
                let maxDiscountGroups = Int(baseAmount / 5.0)
                let maxUsablePointsByAmount = maxDiscountGroups * membershipLevel.pointsPerDiscount
                
                // 取较小值作为最大可用积分
                let maxUsablePoints = min(maxPoints, maxUsablePointsByAmount)
                pointsToUse = min(pointsToUse, maxUsablePoints)
            }
            
            Button(dataManager.currentLanguage == "zh" ? AppStrings.CartView.cancel : AppStrings.CartView.cancelEn, role: .cancel) {
                pointsToUse = 0
            }
        } message: {
            let membershipLevel = dataManager.currentUser?.membershipLevel ?? .lv1
            let ruleText: String = {
                if hasOnlyCashVoucher {
                    return dataManager.currentLanguage == "zh" ? 
                        "Cash Voucher不适用积分抵扣" : 
                        "Points discount not applicable to Cash Voucher"
                } else {
                    return dataManager.currentLanguage == "zh" ? 
                        "每\(membershipLevel.pointsPerDiscount)积分抵扣5元（最低\(membershipLevel.minimumPointsForDiscount)积分起）" : 
                        "Every \(membershipLevel.pointsPerDiscount) points deduct S$5 (minimum \(membershipLevel.minimumPointsForDiscount) points)"
                }
            }()
            Text(ruleText)
        }
        // 移除优惠券使用限制提示弹窗
        // 购物车冲突alert已移除，现在使用自动替换逻辑
        .onChange(of: dataManager.cartItems) { _ in
            // 当购物车内容发生变化时，重新验证已选择的礼券
            validateAppliedCoupon()
        }
    }
    
    // MARK: - 空购物车视图
    private var emptyCartView: some View {
        VStack(spacing: 30) {
            Spacer()
            
            Image(systemName: "cart")
                .font(.system(size: 80))
                .foregroundColor(Color(red: 1.0, green: 0.8, blue: 0.0))  // 亮金色
            
            VStack(spacing: 10) {
                Text(dataManager.currentLanguage == "zh" ? AppStrings.CartView.emptyCartTitle : AppStrings.CartView.emptyCartTitleEn)
                    .font(.title2)
                    .fontWeight(.semibold)
                    .foregroundColor(.white)
                
                Text(dataManager.currentLanguage == "zh" ? AppStrings.CartView.emptyCartMessage : AppStrings.CartView.emptyCartMessageEn)
                    .font(.subheadline)
                    .foregroundColor(.gray)
                    .multilineTextAlignment(.center)
            }
            
            NavigationLink(destination: MenuView()) {
                Text(dataManager.currentLanguage == "zh" ? AppStrings.CartView.browseMenu : AppStrings.CartView.browseMenuEn)
                    .font(.headline)
                    .foregroundColor(Color(red: 0.12, green: 0.12, blue: 0.12))
                    .padding(.horizontal, 30)
                    .padding(.vertical, 15)
                    .background(
                        RoundedRectangle(cornerRadius: 25)
                            .fill(Color(red: 1.0, green: 0.6, blue: 0.2))
                    )
            }
            
            Spacer()
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .padding(.horizontal, 40)
    }
    
    // MARK: - 购物车项目列表
    private var cartItemsList: some View {
        LazyVStack(spacing: 15) {
            ForEach(dataManager.cartItems) { cartItem in
                CartItemRowView(cartItem: cartItem, selectedCoupon: appliedCoupon)
            }
        }
        .padding(.horizontal, 20)
        .padding(.top, 10)
    }
    
    // MARK: - 折扣区域
    private var discountSection: some View {
        VStack(spacing: 15) {
            // 优惠券选择
            if dataManager.currentUser != nil && !hasOnlyCashVoucher {
                Button(action: {
                    showingCouponSelection = true
                }) {
                    HStack {
                        Image(systemName: "ticket.fill")
                            .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                        
                        if let coupon = appliedCoupon {
                            VStack(alignment: .leading, spacing: 2) {
                                Text(coupon.formattedTitle(language: dataManager.currentLanguage))
                                    .font(.subheadline)
                                    .fontWeight(.medium)
                                    .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                                Text("-S$\(calculateCouponDiscount(coupon: coupon), specifier: "%.2f")")
                                    .font(.caption)
                                    .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                            }
                        } else {
                            Text(dataManager.currentLanguage == "zh" ? AppStrings.CartView.selectCoupon : AppStrings.CartView.selectCouponEn)
                                .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                        }
                        
                        Spacer()
                        
                        Image(systemName: "chevron.right")
                            .foregroundColor(.gray)
                    }
                    .padding(15)
                    .background(couponBackground)
                }
            } else {
                HStack {
                    Image(systemName: "ticket.fill")
                        .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                    
                    Text(dataManager.currentLanguage == "zh" ? AppStrings.CartView.selectCoupon : AppStrings.CartView.selectCouponEn)
                        .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                        .strikethrough()
                    
                    let reasonText: String = {
                        if hasOnlyCashVoucher {
                            return dataManager.currentLanguage == "zh" ? "(Cash Voucher不适用优惠券)" : "(Coupons not applicable to Cash Voucher)"
                        } else {
                            return dataManager.currentLanguage == "zh" ? AppStrings.CartView.loginRequired : AppStrings.CartView.loginRequiredEn
                        }
                    }()
                    
                    Text(reasonText)
                        .font(.caption)
                        .foregroundColor(.gray)
                    
                    Spacer()
                    
                    Image(systemName: "chevron.right")
                        .foregroundColor(.gray)
                }
                .padding(15)
                .background(couponBackground)
                .opacity(0.5)
            }
            
            // 积分使用
            if dataManager.currentUser != nil && !hasOnlyCashVoucher {
                Button(action: {
                    showingPointsInput = true
                }) {
                    HStack {
                        Image(systemName: "star.fill")
                            .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                        
                        if pointsToUse > 0 {
                            VStack(alignment: .leading, spacing: 2) {
                                Text(dataManager.currentLanguage == "zh" ? AppStrings.CartView.usePoints : AppStrings.CartView.usePointsEn)
                                    .font(.subheadline)
                                    .fontWeight(.medium)
                                    .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                                let membershipLevel = dataManager.currentUser?.membershipLevel ?? .lv1
                                let discountAmount: Double = {
                                    if hasOnlyCashVoucher {
                                        return 0.0
                                    } else if pointsToUse >= membershipLevel.minimumPointsForDiscount {
                                        let discountGroups = pointsToUse / membershipLevel.pointsPerDiscount
                                        return Double(discountGroups) * 5.0
                                    } else {
                                        return 0.0
                                    }
                                }()
                                Text("\(pointsToUse) \(dataManager.currentLanguage == "zh" ? AppStrings.CartView.points : AppStrings.CartView.pointsEn) (-S$\(discountAmount, specifier: "%.2f"))")
                                    .font(.caption)
                                    .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                            }
                        } else {
                            Text(dataManager.currentLanguage == "zh" ? AppStrings.CartView.usePoints : AppStrings.CartView.usePointsEn)
                                .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                        }
                        
                        Spacer()
                        
                        Text("\(dataManager.currentUser?.points ?? 0) \(dataManager.currentLanguage == "zh" ? "可用" : "available")")
                            .font(.caption)
                            .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                        
                        Image(systemName: "chevron.right")
                            .foregroundColor(.gray)
                    }
                    .padding(15)
                    .background(couponBackground)
                }
            } else {
                HStack {
                    Image(systemName: "star.fill")
                        .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                    
                    Text(dataManager.currentLanguage == "zh" ? "使用积分" : "Use Points")
                        .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                        .strikethrough()
                    
                    let reasonText: String = {
                        if hasOnlyCashVoucher {
                            return dataManager.currentLanguage == "zh" ? "(Cash Voucher不适用积分)" : "(Points not applicable to Cash Voucher)"
                        } else {
                            return dataManager.currentLanguage == "zh" ? "(需登录使用会员优惠)" : "(Login required for member discounts)"
                        }
                    }()
                    
                    Text(reasonText)
                        .font(.caption)
                        .foregroundColor(.gray)
                    
                    Spacer()
                    
                    let availablePoints = hasOnlyCashVoucher ? 0 : (dataManager.currentUser?.points ?? 0)
                    Text("\(availablePoints) \(dataManager.currentLanguage == "zh" ? AppStrings.CartView.available : AppStrings.CartView.availableEn)")
                        .font(.caption)
                        .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                    
                    Image(systemName: "chevron.right")
                        .foregroundColor(.gray)
                }
                .padding(15)
                .background(couponBackground)
                .opacity(0.5)
            }
        }
        .padding(.horizontal, 20)
        .padding(.vertical, 15)
    }
    
    // MARK: - 价格明细
    private var priceBreakdown: some View {
        VStack(spacing: 12) {
            // 显示小计（包括只有Cash Voucher的情况）
            HStack {
                Text(dataManager.currentLanguage == "zh" ? AppStrings.CartView.subtotalBeforeGST : AppStrings.CartView.subtotalBeforeGSTEn)
                    .foregroundColor(.gray)
                Spacer()
                Text("S$\(subtotalBeforeGST, specifier: "%.2f")")
                    .foregroundColor(.white)
            }
            
            // 显示神秘礼物
            if let coupon = appliedCoupon, coupon.code == "MYSTERYGIFT" {
                HStack {
                    Text(dataManager.currentLanguage == "zh" ? "神秘礼物" : "Mystery Gift")
                        .foregroundColor(.gray)
                    Spacer()
                    Text("S$0.00")
                        .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                }
            }
            
            // 显示优惠券折扣
            if discount > 0 {
                HStack {
                    Text(discountDescription)
                        .font(.caption)
                        .foregroundColor(.gray)
                        .lineLimit(1)
                        .truncationMode(.tail)
                    Spacer()
                    Text("-S$\(discount, specifier: "%.2f")")
                        .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                }
                
                HStack {
                    Text(dataManager.currentLanguage == "zh" ? AppStrings.CartView.subtotalAfterDiscount : AppStrings.CartView.subtotalAfterDiscountEn)
                        .foregroundColor(.gray)
                    Spacer()
                    Text("S$\(subtotalAfterDiscount, specifier: "%.2f")")
                        .foregroundColor(.white)
                }
            }
            
            // 显示GST（包括只有Cash Voucher时显示S$0.00）
            HStack {
                Text("GST (9%)")
                    .foregroundColor(.gray)
                Spacer()
                Text("S$\(tax, specifier: "%.2f")")
                    .foregroundColor(.white)
            }
            
            Divider()
                .background(Color.gray)
            
            HStack {
                Text(dataManager.currentLanguage == "zh" ? AppStrings.CartView.total : AppStrings.CartView.totalEn)
                    .font(.headline)
                    .fontWeight(.semibold)
                    .foregroundColor(.white)
                Spacer()
                Text("S$\(total, specifier: "%.2f")")
                    .font(.title2)
                    .fontWeight(.bold)
                    .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
            }
        }
        .padding(20)
        .background(cardBackground)
        .padding(.horizontal, 20)
    }
    
    // MARK: - 结算按钮
    private var checkoutButton: some View {
        Button(action: {
            // 如果购物车只有现金礼券，直接跳到付款页面
            if hasOnlyCashVoucher {
                dataManager.selectedDiningType = .takeaway // 现金礼券默认设置为外带
                showingPayment = true
            } else {
                // 其他商品需要选择用餐类型
                showingReservationFlow = true
            }
        }) {
            Text(dataManager.currentLanguage == "zh" ? AppStrings.CartView.checkout : AppStrings.CartView.checkoutEn)
                .font(.headline)
                .fontWeight(.semibold)
                .foregroundColor(Color(red: 0.12, green: 0.12, blue: 0.12))
                .frame(maxWidth: .infinity)
                .padding(.vertical, 15)
                .background(
                    RoundedRectangle(cornerRadius: 12)
                        .fill(Color(red: 1.0, green: 0.6, blue: 0.2))
                )
        }
        .padding(.horizontal, 20)
        .padding(.vertical, 15)
    }
    
    // 移除showCouponError方法，不再需要显示优惠券错误提示
}

// MARK: - 购物车项目行视图
struct CartItemRowView: View {
    let cartItem: CartItem
    let selectedCoupon: Coupon?
    @EnvironmentObject var dataManager: DataManager
    
    var body: some View {
        HStack(spacing: 15) {
            // 菜品图片
            MenuItemImageView(
                imageSource: cartItem.menuItem.bestImageSource,
                width: 60,
                height: 60,
                cornerRadius: 8,
                contentMode: .fill
            )
            
            // 菜品信息
            VStack(alignment: .leading, spacing: 5) {
                Text(dataManager.currentLanguage == "zh" ? cartItem.menuItem.name : cartItem.menuItem.englishName)
                    .font(.subheadline)
                    .fontWeight(.medium)
                    .foregroundColor(.white)
                    .lineLimit(1)
                
                if let meatType = cartItem.selectedMeatType {
                    Text(dataManager.currentLanguage == "zh" ? meatType.rawValue : meatType.englishName)
                        .font(.caption)
                        .foregroundColor(.gray)
                }
                
                if !cartItem.specialInstructions.isEmpty {
                    Text(cartItem.specialInstructions)
                        .font(.caption)
                        .foregroundColor(.gray)
                        .lineLimit(2)
                }
                
                Text("S$\(cartItem.menuItem.price, specifier: "%.2f") \(dataManager.currentLanguage == "zh" ? AppStrings.CartView.each : AppStrings.CartView.eachEn)")
                    .font(.caption)
                    .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
            }
            
            Spacer()
            
            // 数量控制和价格
            VStack(spacing: 8) {
                HStack(spacing: 10) {
                    Button(action: {
                        if cartItem.quantity > 1 {
                            dataManager.updateCartItemQuantity(cartItem, quantity: cartItem.quantity - 1)
                        } else {
                            dataManager.removeFromCart(cartItem)
                        }
                    }) {
                        Image(systemName: cartItem.quantity > 1 ? "minus.circle.fill" : "trash.fill")
                            .font(.title3)
                            .foregroundColor(cartItem.quantity > 1 ? Color(red: 1.0, green: 0.6, blue: 0.2) : .red)
                    }
                    
                    Text("\(cartItem.quantity)")
                        .font(.subheadline)
                        .fontWeight(.semibold)
                        .foregroundColor(.white)
                        .frame(minWidth: 25)
                    
                    Button(action: {
                        dataManager.updateCartItemQuantity(cartItem, quantity: cartItem.quantity + 1)
                    }) {
                        Image(systemName: "plus.circle.fill")
                            .font(.title3)
                            .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
                    }
                }
                
                Text("S$\(cartItem.totalPrice, specifier: "%.2f")")
                    .font(.subheadline)
                    .fontWeight(.bold)
                    .foregroundColor(Color(red: 1.0, green: 0.6, blue: 0.2))
            }
        }
        .padding(15)
        .background(cardBackground)
    }
}

// MARK: - 优惠券验证方法扩展
extension CartView {
    /// 验证优惠券是否可以使用
    private func canApplyCoupon(_ coupon: Coupon) -> Bool {
        // 使用配置化的过滤逻辑
        return CouponSelectionConfig.shouldShowCoupon(coupon, dataManager: dataManager, isCartSelection: true)
    }
    
    /// 验证当前已选择的礼券是否仍然有效
    private func validateAppliedCoupon() {
        guard let currentCoupon = appliedCoupon else { return }
        
        // 重新验证礼券是否满足使用条件
        if !canApplyCoupon(currentCoupon) {
            // 如果不再满足条件，清除已选择的礼券
            appliedCoupon = nil
            
            // 注释：后台逻辑保持不变，但不显示提示给用户
            // 优惠券会被自动清除，用户可以重新选择
        }
    }
}

// MARK: - 订单类型选择视图
struct OrderTypeSelectionView: View {
    let onDineIn: () -> Void
    let onTakeAway: () -> Void
    let onReservation: () -> Void // 更新预订回调
    @EnvironmentObject var dataManager: DataManager
    
    var body: some View {
        VStack(spacing: 30) {
            Text(dataManager.currentLanguage == "zh" ? AppStrings.CartView.selectOrderType : AppStrings.CartView.selectOrderTypeEn)
                .font(.title2)
                .fontWeight(.bold)
                .foregroundColor(.white)
            
            VStack(spacing: 20) {
                // Dine In 和 Take Away 按钮
                HStack(spacing: 20) {
                    Button(action: onDineIn) {
                        VStack(spacing: 10) {
                            Circle()
                                .fill(Color.orange)
                                .frame(width: 60, height: 60)
                                .overlay(
                                    Image(systemName: "qrcode.viewfinder")
                                        .font(.title)
                                        .foregroundColor(.white)
                                )
                            Text(dataManager.currentLanguage == "zh" ? AppStrings.CartView.dineIn : AppStrings.CartView.dineInEn)
                                .font(.subheadline)
                                .foregroundColor(.white)
                        }
                        .frame(maxWidth: .infinity)
                    }
                    
                    Button(action: onTakeAway) {
                        VStack(spacing: 10) {
                            Circle()
                                .fill(Color.green)
                                .frame(width: 60, height: 60)
                                .overlay(
                                    Image(systemName: "bag.fill")
                                        .font(.title)
                                        .foregroundColor(.white)
                                )
                            Text(dataManager.currentLanguage == "zh" ? AppStrings.CartView.takeAway : AppStrings.CartView.takeAwayEn)
                                .font(.subheadline)
                                .foregroundColor(.white)
                        }
                        .frame(maxWidth: .infinity)
                    }
                }
                .padding(.horizontal, 40)
                
                // 预订按钮（始终显示）
                Button(action: onReservation) {
                    HStack(spacing: 12) {
                        Image(systemName: "calendar.badge.plus")
                            .font(.title2)
                        Text(dataManager.currentLanguage == "zh" ? "预订座位" : "Make Reservation")
                            .font(.headline)
                            .fontWeight(.semibold)
                    }
                    .foregroundColor(.white)
                    .frame(maxWidth: .infinity)
                    .frame(height: 55)
                    .background(
                        LinearGradient(
                            colors: [Color.blue, Color.purple],
                            startPoint: .leading,
                            endPoint: .trailing
                        )
                    )
                    .cornerRadius(27.5)
                }
                .padding(.horizontal, 30)
                
                // 预订说明
                VStack(spacing: 8) {
                    Text(dataManager.currentLanguage == "zh" ? "预订功能" : "Reservation Feature")
                        .font(.subheadline)
                        .fontWeight(.medium)
                        .foregroundColor(.orange)
                    
                    Text(dataManager.currentLanguage == "zh" ? 
                         "无论是否营业时间，您都可以预订座位" : 
                         "You can make reservations anytime, regardless of business hours")
                        .font(.caption)
                        .foregroundColor(.gray)
                        .multilineTextAlignment(.center)
                        .lineLimit(2)
                }
                .padding(.horizontal, 40)
            }
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .background(
            LinearGradient(
                colors: [
                    Color(red: 0.12, green: 0.12, blue: 0.12),
                    Color(red: 0.18, green: 0.16, blue: 0.15)
                ],
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            )
            .ignoresSafeArea()
        )
    }
}

// MARK: - 优惠券行视图
struct CouponRowView: View {
    let coupon: Coupon
    let isSelected: Bool
    let onTap: () -> Void
    @EnvironmentObject var dataManager: DataManager
    @State private var glowAnimation = false
    
    private var gradientColors: [Color] {
        return coupon.getGradientColors()
    }
    
    private var tagColor: Color {
        switch coupon.discountType {
        case .percentage:
            return Color.red
        case .fixedAmount:
            return Color.purple
        }
    }
    
    private var couponValue: String {
        switch coupon.discountType {
        case .percentage:
            return "\(Int(coupon.discountValue))%"
        case .fixedAmount:
            return "S$\(Int(coupon.discountValue))"
        }
    }
    
    var body: some View {
        Button(action: onTap) {
            HStack(spacing: 0) {
                VStack(alignment: .leading, spacing: CouponSelectionConfig.Layout.defaultLineSpacing) {
                    HStack {
                        Text(couponValue)
                            .font(CouponSelectionConfig.Typography.tagFont)
                            .fontWeight(.bold)
                            .foregroundColor(CouponSelectionConfig.Colors.primaryText)
                            .padding(.horizontal, 8)
                            .padding(.vertical, 3)
                            .background(
                                Capsule()
                                    .fill(tagColor)
                            )
                        
                        Spacer()
                    }
                    
                    Text(CouponSelectionConfig.Localization.getCouponTitle(coupon: coupon, language: dataManager.currentLanguage))
                        .font(CouponSelectionConfig.Typography.titleFont)
                        .fontWeight(.bold)
                        .foregroundColor(CouponSelectionConfig.Colors.primaryText)
                        .multilineTextAlignment(.leading)
                        .lineLimit(2)
                    
                    Text(CouponSelectionConfig.Localization.getCouponDescription(coupon: coupon, language: dataManager.currentLanguage))
                        .font(CouponSelectionConfig.Typography.descriptionFont)
                        .foregroundColor(CouponSelectionConfig.Colors.secondaryText)
                        .multilineTextAlignment(.leading)
                        .lineLimit(1)
                    
                    VStack(alignment: .leading, spacing: CouponSelectionConfig.Layout.validUntilLineSpacing) {
                        Spacer(minLength: 0)
                        
                        Text("\(CouponSelectionConfig.Localization.getValidUntilText(language: dataManager.currentLanguage)): \(coupon.validUntil, formatter: DateFormatter.shortDate)")
                            .font(CouponSelectionConfig.Typography.validityFont)
                            .foregroundColor(CouponSelectionConfig.Colors.tertiaryText)
                            .multilineTextAlignment(.leading)
                    }
                }
                .padding(CouponSelectionConfig.CardDimensions.cardPadding)
                .frame(maxWidth: .infinity, alignment: .leading)
                
                VStack {
                    Spacer()
                    
                    HStack(spacing: 8) {
                        Text(couponValue)
                            .font(CouponSelectionConfig.Typography.valueFont)
                            .fontWeight(.black)
                            .foregroundColor(CouponSelectionConfig.Colors.primaryText)
                        
                        Image(systemName: isSelected ? "checkmark.circle.fill" : "circle")
                            .font(CouponSelectionConfig.Typography.valueFont)
                            .foregroundColor(isSelected ? CouponSelectionConfig.Colors.selectedIcon : CouponSelectionConfig.Colors.unselectedIcon)
                    }
                    
                    Spacer()
                }
                .frame(width: CouponSelectionConfig.CardDimensions.selectionAreaWidth)
                .padding(.trailing, CouponSelectionConfig.CardDimensions.cardPadding)
            }
            .frame(height: CouponSelectionConfig.CardDimensions.couponCardHeight)
            .background(
                RoundedRectangle(cornerRadius: CouponSelectionConfig.CardDimensions.cornerRadius)
                    .fill(
                        LinearGradient(
                            colors: gradientColors,
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        )
                    )
                    .overlay(
                        // 内部光晕效果
                        RoundedRectangle(cornerRadius: CouponSelectionConfig.CardDimensions.cornerRadius)
                            .stroke(
                                isSelected ? CouponSelectionConfig.SelectedStyle.innerGlowColor : Color.clear,
                                lineWidth: CouponSelectionConfig.SelectedStyle.innerGlowRadius
                            )
                            .blur(radius: isSelected ? CouponSelectionConfig.SelectedStyle.innerGlowRadius / 2 : 0)
                    )
                    .overlay(
                        // 默认边框
                        RoundedRectangle(cornerRadius: CouponSelectionConfig.CardDimensions.cornerRadius)
                            .stroke(
                                isSelected ? Color.clear : CouponSelectionConfig.UnselectedStyle.borderColor,
                                lineWidth: CouponSelectionConfig.UnselectedStyle.borderWidth
                            )
                    )
                    .overlay(
                        // 选中状态的强化边框
                        RoundedRectangle(cornerRadius: CouponSelectionConfig.CardDimensions.cornerRadius)
                            .stroke(
                                isSelected ? CouponSelectionConfig.SelectedStyle.borderColor : Color.clear,
                                lineWidth: CouponSelectionConfig.SelectedStyle.borderWidth
                            )
                    )
                    .shadow(
                        color: isSelected ? CouponSelectionConfig.SelectedStyle.glowColor : Color.clear,
                        radius: isSelected ? CouponSelectionConfig.SelectedStyle.glowRadius : 0,
                        x: 0,
                        y: 0
                    )
                    .scaleEffect(isSelected ? 1.02 : 1.0)
            )
        }
        .buttonStyle(PlainButtonStyle())
        .animation(
            .spring(
                response: CouponSelectionConfig.Animation.springResponse,
                dampingFraction: CouponSelectionConfig.Animation.springDamping
            ),
            value: isSelected
        )
        .onAppear {
            if isSelected {
                startGlowAnimation()
            }
        }
        .onChange(of: isSelected) { newValue in
            if newValue {
                startGlowAnimation()
            }
        }
    }
    
    private func startGlowAnimation() {
        withAnimation(
            .easeInOut(duration: CouponSelectionConfig.Animation.glowDuration)
            .repeatForever(autoreverses: true)
        ) {
            glowAnimation.toggle()
        }
    }
}

extension DateFormatter {
    static let shortDate: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateStyle = .short
        return formatter
    }()
}

    // MARK: - 卡片背景
    private var cardBackground: some View {
        RoundedRectangle(cornerRadius: 12)
            .fill(LinearGradient(gradient: Gradient(colors: [Color(red: 0.15, green: 0.15, blue: 0.15), Color(red: 0.1, green: 0.1, blue: 0.1), Color(red: 0.05, green: 0.05, blue: 0.05)]), startPoint: .top, endPoint: .bottom))
            .shadow(color: .black.opacity(0.4), radius: 5, x: 0, y: 3)
            .overlay(RoundedRectangle(cornerRadius: 12).stroke(Color.white.opacity(0.1), lineWidth: 1))
    }
    
    // MARK: - 优惠券背景
    private var couponBackground: some View {
        RoundedRectangle(cornerRadius: 12)
            .fill(LinearGradient(gradient: Gradient(colors: [Color(red: 0.15, green: 0.15, blue: 0.15), Color(red: 0.1, green: 0.1, blue: 0.1), Color(red: 0.05, green: 0.05, blue: 0.05)]), startPoint: .top, endPoint: .bottom))
            .shadow(color: .black.opacity(0.4), radius: 5, x: 0, y: 3)
            .overlay(RoundedRectangle(cornerRadius: 12).stroke(Color.white.opacity(0.1), lineWidth: 1))
    }

// 新增 View 扩展用于兼容 scrollIndicators
extension View {
    func applyScrollIndicatorsIfAvailable() -> some View {
        if #available(iOS 16.0, *) {
            return self.scrollIndicators(.automatic, axes: .vertical).tint(Color.green)
        } else {
            return self
        }
    }
}